package com.luxk.db.data.table;

import java.io.IOException;

import com.luxk.db.data.ByteObject;

public class ByteObjectColumn extends ByteObject implements Column {
	
	public static int LONG_LENGTH = 0xFB;
	
	private int length = -1;
	private int colDataOffset = -1;
	
	private int convert1plus3Size(byte b1, byte b2, byte b3) {
		if(b1 != LONG_LENGTH)
			return b1;
		else
			return (b2 << 8 | b3);
	}

	public int getLength() throws IOException {
		if(this.length == -1) {
			if(this.rawBytes == null)
				throw new IOException("ByteObjectColumn not initialized");
			
			this.length = convert1plus3Size(this.rawBytes[this.offset],
					this.rawBytes[this.offset+1],
					this.rawBytes[this.offset+2]);
			assert(this.length <= 0xFFFF);
			
			this.colDataOffset = this.length < LONG_LENGTH ? 1 : 3;
		}
		return this.length;
	}

	public byte[] getData() throws IOException {
		if(this.rawBytes == null) {
			throw new IOException("ByteObjectColumn not initialized");
		}
		
		byte[] ret = new byte[getLength()];
		System.arraycopy(this.rawBytes, this.offset + this.colDataOffset,
				ret, 0, ret.length);

		return ret;
	}

	protected void deserialize() throws IOException {
		if(this.rawBytes == null)
			throw new IOException("ByteObjectColumn not initialized");
		getLength();
	}

	@Override
	public String dump() {
		// TODO Auto-generated method stub
		return null;
	}

}
